package com.cheyun.netsalev3.utils;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.utils.api.ApiStores;
import com.cheyun.netsalev3.utils.api.GlobalConfig;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.exception.ObsException;
import com.obs.services.model.CompleteMultipartUploadRequest;
import com.obs.services.model.InitiateMultipartUploadRequest;
import com.obs.services.model.InitiateMultipartUploadResult;
import com.obs.services.model.PartEtag;
import com.obs.services.model.UploadPartResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.UUID;

public class ImageUploader {
    private String name = "order";
    private Dialog  builder;
    private ProgressBar progressBar;
    private TextView percentText;
//    private static final String KEY = "path";

    private ObsClient obsClient = null;

    public void ossImg(Context context, String pigpath) {
        // 构造上传请求
        String endpoint = ApiStores.OSS_IMAGE_URL;
        // 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的`访问控制`章节
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(ApiStores.OSS_AccessKeyID,ApiStores.OSS_AccessKeySecret);
        OSS oss = new OSSClient(context, endpoint, credentialProvider);
        final Long time = System.currentTimeMillis()/1000;
        PutObjectRequest put = new PutObjectRequest(ApiStores.OSS_bucket, time+name, pigpath);
        showDialogs(context);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                final int count = (int) ((currentSize * 1.0 / totalSize) * 100);
                percentText.post(new Runnable() {//另外一种更简洁的发送消息给ui线程的方法。
                    @Override
                    public void run() {//run()方法会在ui线程执行
                        percentText.setText(count + "%" + "正在上传...");
                    }
                });
                progressBar.post(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setProgress(count);
                    }
                });
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                String imgUrl = ApiStores.HTTP_SERVER_IMAGE_URL + time + name;
                builder.cancel();
                uploadOrderImg(imgUrl);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务
        task.waitUntilFinished(); // 可以等待直到任务完成
    }

    public void obsImg(Context context,String pigpath){

        ObsConfiguration config = new ObsConfiguration();
        config.setSocketTimeout(30000);
        config.setConnectionTimeout(10000);
        config.setEndPoint(GlobalConfig.OBS_ENDPOINT);

        obsClient = new ObsClient(GlobalConfig.OBS_ACCESS_KEYID, GlobalConfig.OBS_ACCESS_KEY_SECRET, config);

//        final Long time = System.currentTimeMillis()/1000;
//        String objectKey = time+name;
//        obsClient.
//        AsyncTask<Void, Void, String> task = new OBSUploadTask();
//        showDialogs(context);
//        task.execute();
    }
    private void uploadOrderImg(final String faceimg){
        System.out.println("上传凭证地址："+faceimg);
//		SharedPreferences shareInfo = getSharedPreferences(Constants.USERINFO, Activity.MODE_PRIVATE);
//		SharedPreferences.Editor editor = shareInfo.edit();
//		editor.putString(Constants.ICON_URL, faceimg);
//		editor.commit();
        LiveEventBus.get().with("uploadOrderImg").postValue(faceimg);
    }

    private void showDialogs(final Context context) {
        builder = new Dialog(context);
        builder.show();
        //builder.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        Window window = builder.getWindow();
        window.setContentView(R.layout.dialog_publish);
        builder.setCanceledOnTouchOutside(true);
        // 为确认按钮添加事件,执行退出应用操作
        progressBar = (ProgressBar) window.findViewById(R.id.progress);
        percentText = (TextView) window.findViewById(R.id.txt_percent);
        ((ImageView) window.findViewById(R.id.btn_cancel)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        builder.setCanceledOnTouchOutside(false);
    }

    class OBSUploadTask extends AsyncTask<Void, Void, String>
    {

        @Override
        protected String doInBackground(Void... params)
        {
            try
            {

                /*
                 * Create bucket
                 */
                obsClient.createBucket(GlobalConfig.OBS_BUCKET);
                final Long time = System.currentTimeMillis()/1000;
                String objectKey = time+name;
                /*
                 * Step 1: initiate multipart upload
                 */
                System.out.println("Step 1: initiate multipart upload \n\n");
                InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest();
                request.setBucketName(GlobalConfig.OBS_BUCKET);
                request.setObjectKey(objectKey);
                InitiateMultipartUploadResult result = obsClient.initiateMultipartUpload(request);

                /*
                 * Step 2: upload a part
                 */
                System.out.println("Step 2: upload part \n\n");
//                UploadPartResult uploadPartResult =
//                        obsClient.uploadPart(GlobalConfig.OBS_BUCKET, objectKey, result.getUploadId(), 1,
//                                new FileInputStream(createSampleFile()));

                /*
                 * Step 3: complete multipart upload
                 */
                System.out.println("Step 3: complete multipart upload \n\n");
                CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest();
                completeMultipartUploadRequest.setBucketName(GlobalConfig.OBS_BUCKET);
                completeMultipartUploadRequest.setObjectKey(objectKey);
                completeMultipartUploadRequest.setUploadId(result.getUploadId());
                PartEtag partEtag = new PartEtag();
//                partEtag.setPartNumber(uploadPartResult.getPartNumber());
//                partEtag.seteTag(uploadPartResult.getEtag());
                completeMultipartUploadRequest.getPartEtag().add(partEtag);
                obsClient.completeMultipartUpload(completeMultipartUploadRequest);

                return "success";
            }
            catch (ObsException e)
            {
//                sb.append("\n\n");
////                sb.append("Response Code:" + e.getResponseCode())
////                        .append("\n\n")
////                        .append("Error Message:" + e.getErrorMessage())
////                        .append("\n\n")
////                        .append("Error Code:" + e.getErrorCode())
////                        .append("\n\n")
////                        .append("Request ID:" + e.getErrorRequestId())
////                        .append("\n\n")
////                        .append("Host ID:" + e.getErrorHostId());
////                return sb.toString();
                return e.toString();
            }
            catch (Exception e)
            {
//                sb.append("\n\n");
//                sb.append(e.getMessage());
                return e.getLocalizedMessage();
            }
            finally
            {
                if (obsClient != null)
                {
                    try
                    {
                        /*
                         * Close obs client
                         */
                        obsClient.close();
                    }
                    catch (IOException e)
                    {
                    }
                }
            }

        }

        @Override
        protected void onPostExecute(String result)
        {
//            TextView tv = (TextView)findViewById(R.id.tv);
//            tv.setText(result);
//            tv.setOnClickListener(null);
//            tv.setMovementMethod(ScrollingMovementMethod.getInstance());

            uploadOrderImg(result);
        }

//        private File createSampleFile()
//                throws IOException
//        {
//            File file = File.createTempFile("obs-android-sdk-", ".txt");
//            file.deleteOnExit();
//
//            Writer writer = new OutputStreamWriter(new FileOutputStream(file));
//            for (int i = 0; i < 1000000; i++)
//            {
//                writer.write(UUID.randomUUID() + "\n\n");
//                writer.write(UUID.randomUUID() + "\n\n");
//            }
//            writer.flush();
//            writer.close();
//
//            return file;
//        }
    }

}
